import axios from 'axios'
export default {
  namespaced: true,
  state: {
    list: []
  },
  getters: {
    totalCount (state) {
      return state.list.reduce((prev, item) => prev + item.count, 0)
    },
    totalPrice (state) {
      return state.list.reduce((prev, item) => prev + (item.count * item.price), 0)
    }
  },
  mutations: {
    updateList (state, list) {
      state.list = list
    },
    setCount (state, data) {
      const obj = state.list.find(item => item.id === data.id)
      obj.count = data.count
    }

  },
  actions: {
    async getCartList (context) {
      const res = await axios.get(' http://localhost:3000/cart')
      console.log(res)
      context.commit('updateList', res.data)
    },
    async updateCount (context, data) {
      // console.log(data)
      await axios.patch(`http://localhost:3000/cart/${data.id}`, {
        count: data.count
      })
      // context.dispatch('getCartList')
      context.commit('setCount', data)
    }
  }
}
